/*
 * $Id: TaskListPane.java 23 2008-12-10 13:26:53Z rdubisz $
 */
package wdp.project;

import java.awt.EventQueue;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import javax.persistence.NoResultException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import wdp.TimeCellRenderer;
import wdp.entities.raw.Task;

public class TaskListPane extends JPanel {

    Logger log = Logger.getLogger(TaskListPane.class.getName());

    public TaskListPane() {
        initComponents();
        TableSelectionListener listener = new TableSelectionListener();
        masterTable.getSelectionModel().addListSelectionListener(listener);
        entityManager.getTransaction().begin();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("db.fdbPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT t FROM Task t WHERE t.started IS NOT NULL");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        jPopupMenu1 = new javax.swing.JPopupMenu();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        saveButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        editButton = new javax.swing.JButton();
        deleteButton = new javax.swing.JButton();
        jDateChooserToday = new com.toedter.calendar.JDateChooser();

        FormListener formListener = new FormListener();

        jPopupMenu1.setName("jPopupMenu1"); // NOI18N

        setName("Form"); // NOI18N

        masterScrollPane.setName("masterScrollPane"); // NOI18N

        masterTable.setColumnSelectionAllowed(true);
        masterTable.setName("masterTable"); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${idProject}"));
        columnBinding.setColumnName("Id Project");
        columnBinding.setColumnClass(wdp.entities.raw.Project.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${started}"));
        columnBinding.setColumnName("Started");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${finish}"));
        columnBinding.setColumnName("Finish");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${description}"));
        columnBinding.setColumnName("Description");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${currentEstimation}"));
        columnBinding.setColumnName("Current Estimation");
        columnBinding.setColumnClass(Integer.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterScrollPane.setViewportView(masterTable);
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(wdp.WdpApp.class).getContext().getResourceMap(TaskListPane.class);
        masterTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        masterTable.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("masterTable.columnModel.title3")); // NOI18N
        masterTable.getColumnModel().getColumn(1).setPreferredWidth(40);
        masterTable.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("masterTable.columnModel.title1")); // NOI18N
        masterTable.getColumnModel().getColumn(1).setCellRenderer(new TimeCellRenderer());
        masterTable.getColumnModel().getColumn(2).setPreferredWidth(40);
        masterTable.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("masterTable.columnModel.title2")); // NOI18N
        masterTable.getColumnModel().getColumn(2).setCellRenderer(new TimeCellRenderer());
        masterTable.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("masterTable.columnModel.title0")); // NOI18N
        masterTable.getColumnModel().getColumn(4).setPreferredWidth(15);
        masterTable.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("masterTable.columnModel.title4")); // NOI18N

        saveButton.setText(resourceMap.getString("saveButton.text")); // NOI18N
        saveButton.setName("saveButton"); // NOI18N
        saveButton.addActionListener(formListener);

        refreshButton.setText(resourceMap.getString("refreshButton.text")); // NOI18N
        refreshButton.setName("refreshButton"); // NOI18N
        refreshButton.addActionListener(formListener);

        editButton.setText(resourceMap.getString("editButton.text")); // NOI18N
        editButton.setName("editButton"); // NOI18N
        editButton.addActionListener(formListener);

        deleteButton.setText(resourceMap.getString("deleteButton.text")); // NOI18N
        deleteButton.setEnabled(false);
        deleteButton.setName("deleteButton"); // NOI18N
        deleteButton.addActionListener(formListener);

        jDateChooserToday.setName("jDateChooserToday"); // NOI18N
        jDateChooserToday.addPropertyChangeListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 478, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(editButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(deleteButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(refreshButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jDateChooserToday, javax.swing.GroupLayout.DEFAULT_SIZE, 214, Short.MAX_VALUE)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {deleteButton, editButton, refreshButton, saveButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(editButton)
                        .addComponent(deleteButton)
                        .addComponent(refreshButton)
                        .addComponent(saveButton))
                    .addComponent(jDateChooserToday, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 103, Short.MAX_VALUE)
                .addContainerGap())
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.beans.PropertyChangeListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == saveButton) {
                TaskListPane.this.saveButtonActionPerformed(evt);
            }
            else if (evt.getSource() == refreshButton) {
                TaskListPane.this.refreshButtonActionPerformed(evt);
            }
            else if (evt.getSource() == deleteButton) {
                TaskListPane.this.deleteButtonActionPerformed(evt);
            }
            else if (evt.getSource() == editButton) {
                TaskListPane.this.editButtonActionPerformed(evt);
            }
        }

        public void propertyChange(java.beans.PropertyChangeEvent evt) {
            if (evt.getSource() == jDateChooserToday) {
                TaskListPane.this.jDateChooserTodayPropertyChange(evt);
            }
        }
    }// </editor-fold>//GEN-END:initComponents

    private class TableSelectionListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (e.getSource() == masterTable.getSelectionModel()) {
                boolean enabled = (masterTable.getSelectedRow() != -1);
                deleteButton.setEnabled(enabled);
            }
        }
    }

  private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed
      entityManager.getTransaction().rollback();
      entityManager.getTransaction().begin();
      list.clear();
      list.addAll(query.getResultList());
  }//GEN-LAST:event_refreshButtonActionPerformed

  private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
      int[] selected = masterTable.getSelectedRows();
      List<Task> toRemove = new ArrayList<Task>(selected.length);
      for (int idx = 0; idx < selected.length; idx++) {
            Task t = list.get(masterTable.convertRowIndexToModel(selected[idx]));
          toRemove.add(t);
          entityManager.remove(t);
      }
      list.removeAll(toRemove);
  }//GEN-LAST:event_deleteButtonActionPerformed

  private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
      entityManager.getTransaction().commit();
      entityManager.getTransaction().begin();
  }//GEN-LAST:event_saveButtonActionPerformed

  private void jDateChooserTodayPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_jDateChooserTodayPropertyChange
      if (evt.getPropertyName().equals("date")) {
          String qString = "SELECT t FROM Task t WHERE t.started BETWEEN '" +
                  new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(jDateChooserToday.getDate()) +
                  "' AND '" +
                  new SimpleDateFormat("yyyy-MM-dd 23:59:59").format(jDateChooserToday.getDate()) +
                  "'";
          log.fine(qString);
          query = entityManager.createQuery(qString);
          entityManager.getTransaction().rollback();
          entityManager.getTransaction().begin();
          list.clear();
          list.addAll(query.getResultList());
          refreshTable();
      }
  }//GEN-LAST:event_jDateChooserTodayPropertyChange

private void editButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editButtonActionPerformed
    Task t = list.get(masterTable.convertRowIndexToModel(masterTable.getSelectedRow()));
    t = TaskEditPane.showTaskEditWindow(t);
    if(t!=null)
        entityManager.persist(t);
    refreshTable();
}//GEN-LAST:event_editButtonActionPerformed

    public void addTask(Task aTask) {
        entityManager.persist(aTask);
        list.add(aTask);
        refreshTable();
    }

    private void refreshTable() {
        int row = list.size() - 1;
        if(row>=0){
            masterTable.setRowSelectionInterval(row, row);
            masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));
        }
    }

    public Task getLastTask() {
        Date day = jDateChooserToday.getDate();
        String qString;
        if (day != null) {
            qString = "SELECT FIRST 1 * FROM Task WHERE started BETWEEN '" +
                    new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(day) +
                    "' AND '" +
                    new SimpleDateFormat("yyyy-MM-dd 23:59:59").format(day) +
                    "' ORDER BY started DESC";
        } else {
            qString = "SELECT FIRST 1 * FROM Task ORDER BY started DESC";
        }
        
        log.fine(qString);
        query = entityManager.createNativeQuery(qString, Task.class);
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        try {
            log.fine("Wybrane ostatnie: "+query.getSingleResult());
            return (Task)query.getSingleResult();
        } catch(NoResultException ex) {
            return null;
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton deleteButton;
    private javax.swing.JButton editButton;
    private javax.persistence.EntityManager entityManager;
    private com.toedter.calendar.JDateChooser jDateChooserToday;
    private javax.swing.JPopupMenu jPopupMenu1;
    private java.util.List<wdp.entities.raw.Task> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.persistence.Query query;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton saveButton;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setContentPane(new TaskListPane());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}
